package com.huarui.company.service;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.ewaf.framework.exception.BizException;
import org.ewaf.framework.service.BaseService;
import org.ewaf.framework.struts2.util.DateFormatUtil;
import org.ewaf.framework.util.BeanUtil;
import org.ewaf.framework.util.MD5Digester;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;

import com.huarui.company.dao.ICompanyDao;
import com.huarui.company.error.CompanyError;
import com.huarui.company.model.Company;
import com.huarui.company.model.CompanyConstant;
import com.huarui.companyconfig.service.CompanyConfigService;
import com.huarui.companydeal.dao.ICompanyDealDao;
import com.huarui.companydeal.model.CompanyDeal;
import com.huarui.department.dao.IDepartmentDao;
import com.huarui.department.model.Department;
import com.huarui.dictionary.DictionaryEnum;
import com.huarui.dictionary.service.DictionaryReadOnlyService.DictionaryResource;
import com.huarui.donation.dao.IDonationDao;
import com.huarui.donation.model.Donation;
import com.huarui.employee.dao.IEmployeeDao;
import com.huarui.employee.dao.IHireHistoryDao;
import com.huarui.employee.model.Employee;
import com.huarui.employee.model.HireHistory;
import com.huarui.partner.dao.IPartnerDao;
import com.huarui.partner.model.Partner;
import com.huarui.permission.service.PermissionService;
import com.huarui.store.dao.IStoreDao;
import com.huarui.store.model.Store;
import com.huarui.user.dao.IUserDao;
import com.huarui.user.error.UserError;
import com.huarui.user.model.SessionMessage;
import com.huarui.user.model.User;
import com.huarui.user.security.UserHolder;
import com.huarui.user.service.SendEmail;
import com.huarui.util.PinyinToolkit;

public class CompanyService extends BaseService {
	
	private final static Logger logger = Logger.getLogger(CompanyService.class);
	/**
	 * 得到操作公司dao
	 * 
	 * @return
	 */
	private ICompanyDao getDao() {

		return (ICompanyDao) dao;
	}

	private IUserDao userDao;
	private IEmployeeDao employeeDao;
	private String activeEmailSubjectTemplate;
	private String activeEmailContentTemplate;
	private String registerSuccessSubjectTemplate;
	private String registerSuccessContentTemplate;
	private String activeUserAndCompanyContentTemplate;
	private String activeUserAndCompanySubjectTemplate;
	private SendEmail sendEmail;
	private IHireHistoryDao hireHistoryDao;
	private IDepartmentDao departmentDao;
	private IStoreDao storeDao;
	private IPartnerDao partnerDao;
	private PermissionService permissionService;
    private CompanyConfigService companyConfigService;
    private IDonationDao donationDao;
	private ICompanyDealDao companyDealDao;

    
	public void setDonationDao(IDonationDao donationDao) {
		this.donationDao = donationDao;
	}


	public void setCompanyDealDao(ICompanyDealDao companyDealDao) {
		this.companyDealDao = companyDealDao;
	}


	public CompanyConfigService getCompanyConfigService() {
		return companyConfigService;
	}


	public void setCompanyConfigService(CompanyConfigService companyConfigService) {
		this.companyConfigService = companyConfigService;
	}


	public PermissionService getPermissionService() {
		return permissionService;
	}


	public void setPermissionService(PermissionService permissionService) {
		this.permissionService = permissionService;
	}


	public void setPartnerDao(IPartnerDao partnerDao) {
		
		this.partnerDao = partnerDao;
	}

	public void setDepartmentDao(IDepartmentDao departmentDao) {
		this.departmentDao = departmentDao;
	}

	public SendEmail getSendEmail() {
		return sendEmail;
	}

	public void setSendEmail(SendEmail sendEmail) {
		this.sendEmail = sendEmail;
	}

	public void setEmployeeDao(IEmployeeDao employeeDao) {
		this.employeeDao = employeeDao;
	}

	/*
	 * public void setTaskQueue(TaskQueue taskQueue) { this.taskQueue =
	 * taskQueue; }
	 */

	public void setUserDao(IUserDao userDao) {
		this.userDao = userDao;
	}

	public void setActiveEmailSubjectTemplate(String activeEmailSubjectTemplate) {
		this.activeEmailSubjectTemplate = activeEmailSubjectTemplate;
	}

	public void setActiveEmailContentTemplate(String activeEmailContentTemplate) {
		this.activeEmailContentTemplate = activeEmailContentTemplate;
	}

	public void setRegisterSuccessSubjectTemplate(
			String registerSuccessSubjectTemplate) {
		this.registerSuccessSubjectTemplate = registerSuccessSubjectTemplate;
	}

	public void setRegisterSuccessContentTemplate(
			String registerSuccessContentTemplate) {
		this.registerSuccessContentTemplate = registerSuccessContentTemplate;
	}

	public void setActiveUserAndCompanyContentTemplate(
			String activeUserAndCompanyContentTemplate) {
		this.activeUserAndCompanyContentTemplate = activeUserAndCompanyContentTemplate;
	}


	public void setActiveUserAndCompanySubjectTemplate(
			String activeUserAndCompanySubjectTemplate) {
		this.activeUserAndCompanySubjectTemplate = activeUserAndCompanySubjectTemplate;
	}


	public void setHireHistoryDao(IHireHistoryDao hireHistoryDao) {
		this.hireHistoryDao = hireHistoryDao;
	}

	public Company getCompanyByName(String name) {

		return this.getDao().getCompanyByName(name);
	}

	public Company getCompanyByTaxCode(String taxCode,Integer paid) {
        
		return this.getDao().getCompanyByTaxCode(taxCode,paid);
	}

	public Company getCompanyByIdWithCreator(Integer id) {
		return this.getDao().getCompanyByIdWithCreator(id);
	}

	public Company getCompanyByCode(String code) {
		return this.getDao().getCompanyByCode(code);
	}

	public Company getCompanyByPYCode(String pyCode) {
		return this.getDao().getCompanyByPYCode(pyCode);
	}

	public Company getCompanyByActivateCode(String activateCode) {
		return this.getDao().getCompanyByActivateCode(activateCode);
	}

	public Company getCompanyByEmail(String email) {
		return this.getDao().getCompanyByEmail(email);
	}

	@SuppressWarnings("unchecked")
	public List<Company> getCompanyByWord(String keyword, int pageSize,
			int start) {

		Map map = new HashMap();

		map.put("keyword", keyword);

		map.put("pageSize", pageSize);

		map.put("start", start);

		return getDao().getCompanysByword(map);
	}

	public void createCompany(final User user , final Company company,
			final Department department, final Store store) {

		transactionTemplate.execute(new TransactionCallback() {

			@Override
			public Object doInTransaction(TransactionStatus status) {
				
				// 已是公司雇员不能注册公司
				if (user.getCompanyId() != 0) {
					throw new RuntimeException(CompanyError.IS_NOT_PERMIT
							.getChError());
				}
				/** 检查此用户是否已注册过公司
				if (getDao().isExistCompanyByCreatorId(company.getCreatorId())) {
					throw new RuntimeException(
							CompanyError.CAN_NOT_REGISTER_AGAIN.getChError());
				}*/
				// 检查公司税号是否已被注册
				if(StringUtils.isNotBlank(company.getTaxCode())){
				if (getDao().isExistCompanyByTaxCode(company.getTaxCode())) {
					throw new RuntimeException(CompanyError.DUPLICATED_TAXCODE
							.getChError());
				}}
				// 检查公司名是否已被注册
				if(StringUtils.isNotBlank(company.getName())){
				if (getDao().isExistCompanyByName(company.getName())) {
					throw new RuntimeException(CompanyError.DUPLICATED_NAME
							.getChError());
				}}
				// 检查公司机构代码是否已被注册
				if(StringUtils.isNotBlank(company.getCode())){
				if (getDao().isExistCompanyByCode(company.getCode())) {
					throw new RuntimeException(CompanyError.DUPLICATED_CODE
							.getChError());
				}}
                 
				company.setPyCode(PinyinToolkit.cn2FirstSpell(company.getName()));
				
				getDao().create(company);
				
				
				companyConfigService.createDefalutCompanyConfig(company.getId());
				
		    	/**
		    	 * 把roleTemplate表中的角色复制到role表中 	 
				  检查Package表,是不是有注册成功后的免费套餐,如果有,就把相应套餐的服务内容添加到companyService中 
                 * 注册公司赠送免费套餐
		    	 */
				permissionService.donateFreePackage2NewRegistCompany(company.getId());
				
			//	permissionService.resume2default(1);
				
				permissionService.createDefaultRolesAndPermissions(company.getId(),company.getCompanyType());
		        

				
				// 保存创建者为公司员工
				user.setCompanyId(company.getId());

				userDao.update(user);

				// 创建缺省部门
				department.setCompanyId(company.getId());
				department.setName("默认部门");
				department.setIsDefault(1);
				department.setPyCode(PinyinToolkit.cn2FirstSpell(department.getName()));
				departmentDao.create(department);
				// 创建缺省仓库
				store.setCompanyId(company.getId());
				store.setIsDefault(1);
				store.setName("默认仓库");
				store.setPyCode(PinyinToolkit.cn2FirstSpell(store.getName()));
				store.setDepartmentId(department.getId());
				storeDao.create(store);
				// 成为公司员工，管理员权限
				Employee employee = new Employee();
				BeanUtil.copyProperties(employee, user);
				employee.setIncumbent(true);
				employee.setGmtHire(new Date());
				employee.setDepartmentId(department.getId());
				employee.setCompanyId(company.getId());
				employee.setUserId(user.getId());
				employee.setCode(String
						.valueOf((int) (1 + Math.random() * 100000000)));
				employee.setRoles(Employee.ROLRS_MANAGER);
				employeeDao.create(employee);

			/**	RoleEmployee roleEmployee =new RoleEmployee();
				
				roleEmployee.setEmployeeId(employee.getId());
		
				List<Role> roles = permissionService.grantCompanyAllRole(company.getId());
				
				for(Role role :roles){
					
					if(role.getIsAdministrator()==1){
						
					//	roleEmployee.setRoleId(role.getId());
						
					}
					
				}*/
				
				/**
				 * 查处公司所拥有的全部角色，并给注册用户赋予管理员的角色
				 */
				
				permissionService.addCompanyAdminRole(employee.getId(),company.getId());
				
			
				HireHistory hireHistory = new HireHistory();
				BeanUtil.copyProperties(hireHistory, employee);
				hireHistory.setGmtCreate(employee.getGmtHire());
				hireHistory.setType(0);
				hireHistoryDao.create(hireHistory);
				
				return status;

			}
		});

	}

	public Company getCompanyByCreateId(Integer createId) {

		return this.getDao().getCompanyByCreatorId(createId);

	}

	public void createOnlyCompany(final Company company,
			final Department department, final Store store) throws Exception {
		transactionTemplate.execute(new TransactionCallback() {

			@Override
			public Object doInTransaction(TransactionStatus status) {
				User user = company.getCreator();
				// 从数据库查处该Email的用户
				User u = userDao.getUserByEmail(user.getEmail());

				// 分开注册个人信息和公司信息

				// 已是公司雇员不能注册公司
				if (user.getCompanyId() != 0) {
					throw new RuntimeException(CompanyError.IS_NOT_PERMIT
							.getChError());
				}
				// 检查此用户是否已注册过公司
				if (getDao().isExistCompanyByCreatorId(u.getId())) {

					throw new RuntimeException(
							CompanyError.CAN_NOT_REGISTER_AGAIN.getChError());
				}
				// 检查用户是否已激活
				if ("0".equals(u.getStatus())) {
					throw new RuntimeException(CompanyError.USER_IS_UNACTIVED
							.getChError());
				}

				// 检查输入的密码是否正确
				if (u != null) {
					if (!MD5Digester.digest(user.getPassword()).equals(
							u.getPassword())) {
						throw new RuntimeException(UserError.WRONG_PASSWORD
								.getChError());
					}
				}
				// 检查公司税号是否已被注册
				if (getDao().isExistCompanyByTaxCode(company.getTaxCode())) {
					throw new RuntimeException(CompanyError.DUPLICATED_TAXCODE
							.getChError());
				}
				// 检查公司名是否已被注册
				if (getDao().isExistCompanyByName(company.getName())) {
					throw new RuntimeException(CompanyError.DUPLICATED_NAME
							.getChError());
				}
				// 检查公司代码是否已被注册
				if (getDao().isExistCompanyByCode(company.getCode())) {
					throw new RuntimeException(CompanyError.DUPLICATED_CODE
							.getChError());
				}

				// 设置公司创建者的用户ID
				company.setCreatorId(u.getId());

				getDao().create(company);
				// 保存创建者为公司员工
				u.setCompanyId(company.getId());

				userDao.update(u);

				// 创建缺省部门
				department.setCompanyId(company.getId());
				department.setName("默认部门");
				departmentDao.create(department);
				// 创建缺省仓库
				store.setCompanyId(company.getId());
				store.setName("默认仓库");
				store.setDepartmentId(department.getId());
				storeDao.create(store);
				// 成为公司员工，管理员权限
				Employee employee = new Employee();
				BeanUtil.copyProperties(employee, u);
				employee.setIncumbent(true);
				employee.setGmtHire(new Date());
				;
				employee.setDepartmentId(department.getId());
				employee.setCompanyId(company.getId());
				employee.setUserId(u.getId());
				employee.setCode(String
						.valueOf((int) (1 + Math.random() * 100000000)));
				employee.setRoles(Employee.ROLRS_MANAGER);
				employeeDao.create(employee);
				HireHistory hireHistory = new HireHistory();
				BeanUtil.copyProperties(hireHistory, employee);
				hireHistory.setGmtCreate(employee.getGmtHire());
				hireHistory.setType(0);
				hireHistoryDao.create(hireHistory);

				return status;
			}
		});

	}

	public void createUserAndCompany(final Company company,
			final Department department, final Store store) throws Exception {
		transactionTemplate.execute(new TransactionCallback() {

			@Override
			public Object doInTransaction(TransactionStatus status) {
				User user = company.getCreator();

				// 同时注册个人信息和公司信息
				// 检查个人邮件地址是否重复
				User u = userDao.getUserByEmail(user.getEmail());
				if (u != null) {
					throw new BizException(UserError.DUPLICATED_EMAIL);
				}
				// 密码保存到数据库前用MD5加密
				user.setPassword(MD5Digester.digest(user.getPassword()));

				userDao.create(user);
				// 检查公司税号是否已被注册
				if (getDao().isExistCompanyByTaxCode(company.getTaxCode())) {
					throw new BizException(CompanyError.DUPLICATED_TAXCODE);
				}
				// 检查公司名是否已被注册
				if (getDao().isExistCompanyByName(company.getName())) {
					throw new BizException(CompanyError.DUPLICATED_NAME);
				}
				// 检查公司代码是否已被注册
				if (getDao().isExistCompanyByCode(company.getCode())) {
					throw new BizException(CompanyError.DUPLICATED_CODE);
				}

				// 设置公司创建者的用户ID
				company.setCreatorId(user.getId());

				getDao().create(company);
				// 保存创建者为公司员工
				user.setCompanyId(company.getId());

				userDao.update(user);
				// 创建缺省部门
				department.setCompanyId(company.getId());
				department.setName("默认部门");
				departmentDao.create(department);
				// 创建缺省仓库
				store.setCompanyId(company.getId());
				store.setName("默认仓库");
				store.setDepartmentId(department.getId());
				storeDao.create(store);
				// 成为公司员工，管理员权限
				Employee employee = new Employee();
				BeanUtil.copyProperties(employee, user);
				employee.setIncumbent(true);
				employee.setGmtHire(new Date());
				employee.setDepartmentId(department.getId());
				employee.setCompanyId(company.getId());
				employee.setUserId(user.getId());
				employee.setCode(String
						.valueOf((int) (1 + Math.random() * 100000000)));
				employee.setRoles(Employee.ROLRS_MANAGER);
				employeeDao.create(employee);
				HireHistory hireHistory = new HireHistory();
				BeanUtil.copyProperties(hireHistory, employee);
				hireHistory.setGmtCreate(employee.getGmtHire());
				hireHistory.setType(0);
				hireHistoryDao.create(hireHistory);

				return status;
			}
		});

	}

	/**
	 * 发送激活邮件
	 * 
	 * @throws Exception
	 */
	public void sendActiveEmail(Company company, boolean withUser) {
		Map<String, String> data = new HashMap<String, String>();
		data.put("userName", company.getCreator().getName());
		data.put("charset", "UTF-8");
		if (withUser) {
			data
					.put("userActivateCode", company.getCreator()
							.getActivateCode());
		}
		data.put("companyActivateCode", company.getActivateCode());
		data.put("subjectTemplate", activeEmailSubjectTemplate);
		data.put("contentTemplate", activeEmailContentTemplate);
		data.put("recipients", company.getCreator().getEmail());
		sendEmail.send(data);
	}

	/**
	 * 激活公司
	 */
	public void activeCompany(final Company company) {
		if (company == null) {
			throw new BizException(CompanyError.COMPANY_IS_NOT_EXIST);
		}
		if (CompanyConstant.STATUS_ACTIVED.equals(company.getStatus())) {
			throw new BizException(CompanyError.ALREADY_BE_ACTIVED);
		}

		User user = (User) userDao.getById(company.getCreatorId());
		company.setCreator(user);
		// 检查公司创建者账号是否已激活
		if ("0".equals(user.getStatus())) {
			throw new BizException(CompanyError.USER_IS_UNACTIVED);
		}
		company.setStatus(CompanyConstant.STATUS_ACTIVED);
		company.setActivateCode(null);
		try {
			getDao().update(company);
		} catch (Exception e) {

			// 得到有业务往来的在线公司
			List<Partner> partnerList = partnerDao.getPartnerByOwnerId(user
					.getId());
			if (partnerList != null) {
				for (Partner partner : partnerList) {
					if (partner.getCompanyId() != null) {
						// 发送注册成功通知
						this.sendRegisterSuccess(partner, user, company);
					}
				}
			}
			throw new RuntimeException("激活公司失败");
		}

	}

	/**
	 * 通知往来的在线公司，该公司已注册
	 */
	public void sendRegisterSuccess(Partner partner, User user, Company company) {
		Map<String, String> data = new HashMap<String, String>();
		data.put("partnerName", partner.getName());
		data.put("companyName", company.getName());
		data.put("userName", user.getName());
		data.put("subjectTemplate", registerSuccessSubjectTemplate);
		data.put("contentTemplate", registerSuccessContentTemplate);
		data.put("recipients", partner.getEmail());
		sendEmail.send(data);
	}

	public void setStoreDao(IStoreDao storeDao) {
		this.storeDao = storeDao;
	}

	public void updateCompanny(Company company) {

		this.getDao().updateCompany(company);

	}
	
	public Company getBySimpleId(Integer id){
		
		return this.getDao().getBySimpleId(id);
		
	}


	public Integer getCompanyCountByConditions(Map<String, Object> jsonObject) {
		return getDao().getCompanyCountByConditions(jsonObject);
	}


	public List<Company> getAllCompanyByConditions(Map<String, Object> jsonObject) {
		return getDao().getCompanyByConditions(jsonObject);
		
		
	}

	public List<Company> getByContactorIdentityCode(String contactorIdentityCode,Integer paid){
		
		
		List<Company>  companyList = this.getDao().getByContactorIdentityCode(contactorIdentityCode,paid);
		
		return companyList;
	}


	public  List<Company> getLikeContactorIdentityCode(String contactorIdentityCode){
		
		
		return this.getDao().getLikeContactorIdentityCode(contactorIdentityCode);
	}
	
	public  List<Company> getCompanyLikeTaxCode(String taxCode){
		
		return this.getDao().getCompanyLikeTaxCode(taxCode);
	}
	
	public void addCompanyBalance(String queryParam,final String ip) {
		JSONObject jsonObject = JSONObject.fromObject(queryParam);
		final Integer companyId = jsonObject.getInt("companyId");
		final BigDecimal sum =new BigDecimal(jsonObject.getDouble("sum"));
		final String description=jsonObject.getString("description");
		try {
			transactionTemplate.execute(new TransactionCallback() {			
				@Override
				public Object doInTransaction(TransactionStatus status) {
					Company company = getDao().getCompanyByIdForUpdate(companyId);
					BigDecimal balance = company.getBalance().add(sum);
					company.setBalance(balance);
					getDao().updateCompany(company);
					Donation donation=createDonation(ip,company.getBalance(),sum,description,company);
					createCompanyDeal(ip,balance,sum,donation.getId(),description,company);
					return null;
				}
			});
			
		} catch (Exception e) {
			logger.error("赠送U币错误", e);
		}
	}

	private Donation createDonation(String ip,BigDecimal balance,BigDecimal sum,String description,Company company){
		SessionMessage sm=UserHolder.getCurrentSessionMessage();
		Donation donation=new Donation();
		donation.setCompanyId(company.getId());
		donation.setCompanyName(sm.getCompanyName());
		donation.setIp(ip);
		donation.setCreatorId(sm.getUserId());
		donation.setCreatorName(sm.getUserName());
		donation.setVolume(sum);
		donation.setBeginBalance(balance.subtract(sum));
		donation.setEndBalance(balance);
		donation.setDescription(description);
		donationDao.create(donation);
		return donation;
	}
	private void createCompanyDeal(String ip,BigDecimal balance,BigDecimal sum,Integer dealId,String description,Company company){
		SessionMessage sm=UserHolder.getCurrentSessionMessage();
		CompanyDeal companyDeal=new CompanyDeal();
		companyDeal.setCompanyId(company.getId());
		companyDeal.setIp(ip);
		companyDeal.setCreatorId(sm.getUserId());
		companyDeal.setCreatorName(sm.getUserName());
		companyDeal.setBorrow(BigDecimal.ZERO);
		companyDeal.setLoan(sum);
		companyDeal.setBeginBalance(balance.subtract(sum));
		companyDeal.setEndBalance(balance);
		companyDeal.setDealType(CompanyDeal.DEALTYPE_DONEE);
		companyDeal.setDealId(dealId);
		companyDeal.setDealName(DictionaryResource.getDictionaryValue(DictionaryEnum.GROUP_COMPANYDEAL_DEALTYPE, String.valueOf(CompanyDeal.DEALTYPE_DONEE)));
		companyDeal.setDescription(description);
		companyDealDao.create(companyDeal);
	}

	/**
	 * 同时注册公司和用户
	 * @param user
	 * @param company
	 */
	public void createUserAndCompany(final User user , final Company company) {

		transactionTemplate.execute(new TransactionCallback() {

			@Override
			public Object doInTransaction(TransactionStatus status) {

				userDao.create(user);
				company.setCertifyingStatus(0);
				company.setStatus(CompanyConstant.STATUS_ACTIVED);
		        company.setContactor(user.getName());
		        company.setEmail(user.getEmail());
				company.setCreator(user);
				company.setCreatorId(user.getId());
		        company.setRequestRealType(1);
		        company.setRequestCompanyType(0);
				
				company.setPyCode(PinyinToolkit.cn2FirstSpell(company.getName()));
				
				dao.create(company);
				
				
				companyConfigService.createDefalutCompanyConfig(company.getId());
				
		    	/**
		    	 * 把roleTemplate表中的角色复制到role表中 	 
				  检查Package表,是不是有注册成功后的免费套餐,如果有,就把相应套餐的服务内容添加到companyService中 
                 * 注册公司赠送免费套餐
		    	 */
				permissionService.donateFreePackage2NewRegistCompany(company.getId());
				
				
				permissionService.createDefaultRolesAndPermissions(company.getId(),company.getCompanyType());
		        

				
				// 保存创建者为公司员工
				user.setCompanyId(company.getId());

				userDao.update(user);
               
				Department department = new Department();
				
				// 创建缺省部门
				department.setCompanyId(company.getId());
				department.setName("默认部门");
				department.setIsDefault(1);
				department.setPyCode(PinyinToolkit.cn2FirstSpell(department.getName()));
				departmentDao.create(department);
				// 创建缺省仓库
				Store store=new Store();
				store.setCompanyId(company.getId());
				store.setIsDefault(1);
				store.setName("默认仓库");
				store.setPyCode(PinyinToolkit.cn2FirstSpell(store.getName()));
				store.setDepartmentId(department.getId());
				storeDao.create(store);
				// 成为公司员工，管理员权限
				Employee employee = new Employee();
				BeanUtil.copyProperties(employee, user);
				employee.setIncumbent(true);
				employee.setGmtHire(new Date());
				employee.setDepartmentId(department.getId());
				employee.setCompanyId(company.getId());
				employee.setUserId(user.getId());
				employee.setCode(String
						.valueOf((int) (1 + Math.random() * 100000000)));
				employee.setRoles(Employee.ROLRS_MANAGER);
				employeeDao.create(employee);

				permissionService.addCompanyAdminRole(employee.getId(),company.getId());
				
			
				HireHistory hireHistory = new HireHistory();
				BeanUtil.copyProperties(hireHistory, employee);
				hireHistory.setGmtCreate(employee.getGmtHire());
				hireHistory.setType(0);
				hireHistoryDao.create(hireHistory);
				
				return status;

			}
		});

	}
	
	
	public Map<String, Object> modifyCompany(final List<String>filePaths,final Company newCompany ,final Integer companyId) {

		 final Map<String, Object> resultMap = new HashMap<String, Object>();

			transactionTemplate.execute(new TransactionCallback() {			
				@Override
				public Object doInTransaction(TransactionStatus status) {
					Company oldCompany = getDao().getCompanyByIdForUpdate(companyId);
			
				    
					if(StringUtils.isNotBlank(filePaths.get(0))){
						
						    newCompany.setContactorIdPath(filePaths.get(0));

						}
						if(StringUtils.isNotBlank(filePaths.get(1))){
							newCompany.setBusinessLicensePath(filePaths.get(1));
						}
						if(StringUtils.isNotBlank(filePaths.get(2))){
							newCompany.setTaxCertificationPath(filePaths.get(2));
					}
	                  //System.out.println(DateFormatUtil.dateSecond(newCompany.getGmtModify()));
	                  //System.out.println(DateFormatUtil.dateSecond(oldCompany.getGmtModify()));
						if(!DateFormatUtil.dateSecond(newCompany.getGmtModify()).equals(DateFormatUtil.dateSecond(oldCompany.getGmtModify()))){
										
							resultMap.put("already_be_modify", CompanyError.ALREADY_BE_MODIFY.getChError());
							
							return resultMap;
							
						}
						
					
					try {
						BeanUtils.copyProperties(oldCompany, newCompany);					

						getDao().updateCompany(oldCompany);
					} catch (Exception e) {
						logger.debug(e.getMessage());
					}

	
					return null;
				}
		
			});
			
         return resultMap;
	}
	
	
	/**
	 * 发送激活邮件
	 */
	public void sendActiveEmail(User user,Company company) {
		Map<String, String> data = new HashMap<String, String>();

		data.put("charset", "UTF-8");
		data.put("recipients", user.getEmail());
		data.put("subjectTemplate", activeUserAndCompanySubjectTemplate);
		data.put("contentTemplate", activeUserAndCompanyContentTemplate);
		data.put("userName", user.getName());
		data.put("companyName",company.getName());
		data.put("activeCode", user.getActivateCode());
		sendEmail.send(data);
		/*
		 * Task task = new Task(); task.setType("commonEmail");
		 * task.setId(UUID.randomUUID().toString()); task.setExecTime(8);
		 * task.setDataMap(data); taskQueue.addTask(task);
		 */
	}
	
	
}
